package top.jnaw.jee.utils.jpush;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.connection.NativeHttpClient;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
import java.util.Map;
import top.jnaw.jee.platform.Consts;
import top.jnaw.jee.utils.Log;
import top.jnaw.jee.utils.ModelResult;
import top.jnaw.jee.utils.Shiros;
import top.jnaw.jee.utils.Strings;

/**
 * Copyright (C) 2018 版权所有。 <p> 文件名： 文件功能描述：极光推送
 *
 * @author lc  2018/6/25 11:48 创建内容： <p> <p> 修改标识： 修改原因：
 */
public class JPushs {

  public static long sendCount = 0;

  public static PushPayload buildPushObject_all_all_alert() {
    return PushPayload.alertAll("ceshi222222222");
  }

  public static PushPayload buildPushObject_android_tag_alertWithTitle() {
    return PushPayload.newBuilder()
        .setPlatform(Platform.android())
//        .setAudience(Audience.tag("tag1"))
        .setNotification(Notification.android("111", "2223", null))
        .build();
  }

  public static PushPayload buildPushObject_all_alias_alert() {
    return PushPayload.newBuilder()
        .setPlatform(Platform.all())
        .setAudience(Audience.alias("alias1"))
        .setNotification(Notification.alert("1122"))
        .build();
  }

  /**
   * 发送极光推送
   */
//  public static void sendjpush(boolean local, String title, String alert,
//      List<Users> pushUsers, Map<String, String> extras) {
//    //发送极光推送
//    if (null != pushUsers && pushUsers.size() > 0) {
//      // [Neo] .TODO change admin for update!
//      int senderUid = 1;
//
//      if (!local) {
//        String username = Shiros.getUser();
//        if (null != username) {
//          Users u = Users.getByUsername(username);
//          if (null != u && u.getId() > 0) {
//            senderUid = u.getId();
//            for (Users users : pushUsers) {
//              ModelResult result = NewsCenter
//                  .add(senderUid, users.getUsername(), alert, title, extras);
//              Log.e("news_center add result::" + result);
//            }
//            pushUsers = Strings.search(u.getUsername(), pushUsers);
//          }
//        }
//      }
//      Log.e("pushUsers::" + pushUsers.toString());
//      for (Users u : pushUsers) {
//        sendPush(senderUid, u.getUsername(), alert, title, extras);
//      }
//    }
//  }
//
//  public static void sendjpush(String title, String alert,
//      List<Users> pushUsers, Map<String, String> extras) {
//    sendjpush(false, title, alert, pushUsers, extras);
//  }
  public static void sendPush(int senderUid, String alias, String alert,
      String title,
      Map<String, String> extras) {

    JPushClient jpushClient = new JPushClient(
        Consts.JPUSH_MASTER_SECRET,
        Consts.JPUSH_APP_KEY, null,
        ClientConfig.getInstance());

    PushPayload payload = PushPayload.newBuilder()
        .setPlatform(Platform.all())
        .setAudience(Audience.alias(alias))
        .setNotification(Notification.android(alert, title, extras))
        .build();
    JSONObject resultJson = null;
    try {
      PushResult result = jpushClient.sendPush(payload);
      Log.w("Got result -::: " + result);
      resultJson = Strings.toJSONObject(result.toString());
      Log.w("Got result - " + resultJson);
    } catch (APIConnectionException e) {
      // Connection error, should retry later
      Log.e("Connection error, should retry later");
//      e.printStackTrace();

    } catch (APIRequestException e) {
      // Should review the error, and fix the request
      Log.e("Should review the error, and fix the request");
//      e.printStackTrace();
      Log.w("HTTP Status: " + e.getStatus());
      Log.w("Error Code: " + e.getErrorCode());
      Log.w("Error Message: " + e.getErrorMessage());
      Log.w("Error MessageId: " + e.getMsgId());
    }
//    if (null != resultJson) {
//      MessageHistory.add(resultJson.getString("msg_id"),
//          resultJson.getIntValue("sendno"), senderUid,
//          resultJson.getIntValue("statusCode"), alias, alert, title, extras);
//    } else {
//      MessageHistory.add("",
//          0, senderUid,
//          1011, alias, alert, title, extras);
//    }
  }

  /**
   * 开启线程
   */
  public static void testSendPush(String alias, String alert, String title,
      Map<String, String> extras) {
    ClientConfig clientConfig = ClientConfig.getInstance();
    final JPushClient jpushClient = new JPushClient(
        "dbd618fb478928f7dbdfc131",
        "237a7dd4320e03dcc9301420", null,
        ClientConfig.getInstance());
    String authCode = ServiceHelper
        .getBasicAuthorization("237a7dd4320e03dcc9301420",
            "dbd618fb478928f7dbdfc131");
    NativeHttpClient httpClient = new NativeHttpClient(authCode, null,
        clientConfig);
    jpushClient.getPushClient().setHttpClient(httpClient);
    final PushPayload payload = PushPayload.newBuilder()
        .setPlatform(Platform.all())
        .setAudience(Audience.alias(alias))
        .setNotification(Notification.android(alert, title, extras))
        .build();

    for (int i = 0; i < 10; i++) {
      Thread thread = new Thread() {
        public void run() {
          for (int j = 0; j < 200; j++) {
            long start = System.currentTimeMillis();
            try {
              PushResult result = jpushClient.sendPush(payload);
              Log.w("Got result - " + result);

            } catch (APIConnectionException e) {
              Log.e("Connection error. Should retry later. ");
              Log.e("Sendno: " + payload.getSendno());

            } catch (APIRequestException e) {
              Log.e(
                  "Error response from JPush server. Should review and fix it. ");
              Log.i("HTTP Status: " + e.getStatus());
              Log.i("Error Code: " + e.getErrorCode());
              Log.i("Error Message: " + e.getErrorMessage());
              Log.i("Msg ID: " + e.getMsgId());
              Log.e("Sendno: " + payload.getSendno());
            }

            System.out.println(
                "耗时" + (System.currentTimeMillis() - start) + "毫秒 sendCount:"
                    + (++sendCount));
          }
        }
      };
      thread.start();
    }

//        // For push, all you need do is to build PushPayload object.
//        PushPayload payload = buildPushObject_all_alias_alert();
//        try {
//            PushResult result = jpushClient.sendPush(payload);
//            Log.i("Got result - " + result);
//            // 如果使用 NettyHttpClient，需要手动调用 close 方法退出进程
//            // If uses NettyHttpClient, call close when finished sending request, otherwise process will not exit.
//            // jpushClient.close();
//        } catch (APIConnectionException e) {
//            Log.e("Connection error. Should retry later. ", e);
//            Log.e("Sendno: " + payload.getSendno());
//
//        } catch (APIRequestException e) {
//            Log.e("Error response from JPush server. Should review and fix it. ", e);
//            Log.i("HTTP Status: " + e.getStatus());
//            Log.i("Error Code: " + e.getErrorCode());
//            Log.i("Error Message: " + e.getErrorMessage());
//            Log.i("Msg ID: " + e.getMsgId());
//            Log.e("Sendno: " + payload.getSendno());
//        }
  }


}
